import React, { Fragment } from "react";
import { Row, Col, Affix, Spin } from "antd";
import { useHistory } from "react-router-dom";
import { PaymentCard, ProductList } from "../../components";
import { useSelector } from "../../redux/hooks";
import { useDispatch } from "react-redux";
import {
  clearShoppingCart,
  checkout,
} from "../../redux/shoopingCart/shoopingCartSlice";
import { MainLayout } from "../../layouts/mainLayout";
import styles from "./ShoppingCart.module.scss";
export const ShoppingCart: React.FC = () => {
  const dispatch = useDispatch();
  const history = useHistory();
  const loading = useSelector((s) => s.shopingCart.loading);
  const shoppingCartItems = useSelector((s) => s.shopingCart.items);
  const jwt = useSelector((s) => s.user.token) as string;
  // 清空购物车
  const onHandleShoppingCartClear = () => {
    if (typeof jwt === "string") {
      dispatch(
        clearShoppingCart({
          jwt,
          itemIds: shoppingCartItems.map((item) => item.id),
        })
      );
    }
  };
  // 生成订单
  const onHandleCheckCart = () => {
    if (shoppingCartItems.length > 0) {
      dispatch(checkout(jwt));
      history.push("/placeOrder");
    } else {
      return true;
    }
  };
  if (loading) {
    return (
      <Spin
        size="large"
        tip="loading..."
        style={{
          marginTop: 200,
          marginLeft: "auto",
          marginBottom: 200,
          marginRight: "auto",
          width: "100%",
        }}
      />
    );
  }
  return (
    <Fragment>
      <MainLayout>
        <Row>
          {/* 购物清单 */}
          <Col span={16}>
            <div className={styles["product-list-container"]}>
              <ProductList
                data={shoppingCartItems.map((item) => item.touristRoute)}
              />
            </div>
          </Col>
          {/* 支付卡组件 */}
          <Col span={8}>
            <Affix>
              <div className={styles["payment-card-container"]}>
                <PaymentCard
                  loading={loading}
                  originalPrice={shoppingCartItems
                    .map((item) => item.originalPrice)
                    .reduce((a, b) => a + b, 0)}
                  price={shoppingCartItems
                    .map((item) =>
                      item.originalPrice * item.discountPresent
                        ? item.discountPresent
                        : 1
                    )
                    .reduce((a, b) => a + b, 0)}
                  onCheckout={onHandleCheckCart}
                  onShoppingCartClear={onHandleShoppingCartClear}
                />
              </div>
            </Affix>
          </Col>
        </Row>
      </MainLayout>
    </Fragment>
  );
};
